package server.gashapon;

import client.MapleCharacter;
import database.BeePool;
import handling.world.World.Broadcast;
import server.MapleItemInformationProvider;
import server.Randomizer;
import tools.FilePrinter;
import tools.FileoutputUtil;
import tools.MaplePacketCreator;
import tools.Pair;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;

public class Gashapon {
    private int id;
    private int npcId;
    private String name;
    private List<Pair<Long, GashaponReward>> items;

    public Gashapon(int id, int npcId, String name) {
        this.items = (List<Pair<Long, GashaponReward>>) new LinkedList();
        this.id = id;
        this.npcId = npcId;
        this.name = name;
        this.reloadItems();
    }

    public int getId() {
        return this.id;
    }

    public int getNpcId() {
        return this.npcId;
    }

    public String getName() {
        return this.name;
    }

    public GashaponReward generateReward() {
        if (this.items.isEmpty()) {
            this.reloadItems();
        }
        Iterator<Pair<Long, GashaponReward>> iterator = this.items.iterator();
        long total = ((Long) (this.items.get(this.items.size() - 1)).left).longValue();
        Long n = Long.valueOf(Math.abs(Randomizer.nextLong() * System.currentTimeMillis() + 47L * System.currentTimeMillis()) % total);
        while (iterator.hasNext()) {
            Pair<Long, GashaponReward> c = iterator.next();
            if (n.longValue() <= ((Long) c.left).longValue()) {
                return (GashaponReward) c.right;
            }
        }
        return null;
    }

    public void reloadItems() {
        long chanceTotal = 0L;
        try (Connection con = BeePool.getConnection();
             PreparedStatement ps = con.prepareStatement("SELECT * FROM gashapon_items WHERE gashaponsid = ? ORDER BY itemid ASC")) {
            ps.setInt(1, this.getId());
            ResultSet rs = ps.executeQuery();
            while (rs.next()) {
                GashaponReward reward = new GashaponReward(rs.getInt("itemid"), rs.getInt("chance"), rs.getBoolean("showmsg"), rs.getInt("quantity"));
                chanceTotal += (long) reward.getChance();
                this.items.add(new Pair(Long.valueOf(chanceTotal), reward));
            }
            rs.close();
            ps.close();
            
        } catch (SQLException ex) {
            FilePrinter.printError("Gashapon.txt", (Throwable) ex, "reloadItems");
        }
    }

    public String ShowItem(String type) {
        StringBuilder sb = new StringBuilder();
        Iterator<Pair<Long, GashaponReward>> iterator = this.items.iterator();
        sb.append("#b此转蛋机物品有:\r\n");
        while (iterator.hasNext()) {
            Pair<Long, GashaponReward> c = iterator.next();
            if (MapleItemInformationProvider.getInstance().itemExists(((GashaponReward) c.right).getItemId()) && ((GashaponReward) c.right).getChance() > 0) {
                switch (type) {
                    case "1": {
                        sb.append("#v" + ((GashaponReward) c.right).getItemId() + "#");
                        continue;
                    }
                    case "2": {
                        sb.append("#v" + ((GashaponReward) c.right).getItemId() + "#  道具名称: #z" + ((GashaponReward) c.right).getItemId() + "#\r\n");
                        continue;
                    }
                    case "GM": {
                        sb.append("#L" + ((GashaponReward) c.right).getItemId() + "##v" + ((GashaponReward) c.right).getItemId() + "##z" + ((GashaponReward) c.right).getItemId() + "# 机率:" + ((GashaponReward) c.right).getChance() + "# 数量:" + ((GashaponReward) c.right).getQuantity() + "(点選更改)\r\n");
                        continue;
                    }
                    default: {
                        sb.append("指定显示型态错误!");
                        continue;
                    }
                }
            }
        }
        if (type == "GM") {
            sb.append("\r\n#b#L10000#我要新增转蛋机物品!!#l\r\n");
        }
        return sb.toString();
    }

    public String ShowItem_GM() {
        StringBuilder sb = new StringBuilder();
        Iterator<Pair<Long, GashaponReward>> iterator = this.items.iterator();
        sb.append("#b此转蛋机物品有:\r\n");
        while (iterator.hasNext()) {
            Pair<Long, GashaponReward> c = iterator.next();
            if (MapleItemInformationProvider.getInstance().itemExists(((GashaponReward) c.right).getItemId())) {
                sb.append("#L" + this.items.size() + "##v" + ((GashaponReward) c.right).getItemId() + "##z" + ((GashaponReward) c.right).getItemId() + "# 机率:" + ((GashaponReward) c.right).getChance() + "# 数量:" + ((GashaponReward) c.right).getQuantity() + "(点選更改)\r\n");
            }
        }
        return sb.toString();
    }

    public void ChangeChance(MapleCharacter chr, int itemid, int chance) {
        try (Connection con = BeePool.getConnection();
             PreparedStatement ps = con.prepareStatement("UPDATE gashapon_items SET chance = ? WHERE gashaponsid = ? AND itemid = ?")) {
            ps.setInt(1, chance);
            ps.setInt(2, this.getId());
            ps.setInt(3, itemid);
            ps.executeUpdate();
            ps.close();
            
        } catch (SQLException ex) {
            System.out.println("Error GashaponChance" + ex);
            FilePrinter.printError("GashaponChance.txt", (Throwable) ex, "GashaponChance has SQL Exception");
        }
        Broadcast.broadcastGMMessage(MaplePacketCreator.serverNotice(6, "[GM 密语系统] " + chr.getName() + "  更改物品:" + MapleItemInformationProvider.getInstance().getName(itemid) + " 机率更改为" + chance));
        FileoutputUtil.logToFile("logs/GM_LOG/GM更改转蛋物机率.txt", "\r\n" + FileoutputUtil.NowTime() + "GM: " + chr.getName() + "  更改物品:" + MapleItemInformationProvider.getInstance().getName(itemid) + " 机率更改为" + chance);
    }

    public void ChangeQuantity(MapleCharacter chr, int itemid, int quantity) {
        try (Connection con = BeePool.getConnection();
             PreparedStatement ps = con.prepareStatement("UPDATE gashapon_items SET quantity = ? WHERE gashaponsid = ? AND itemid = ?")) {
            ps.setInt(1, quantity);
            ps.setInt(2, this.getId());
            ps.setInt(3, itemid);
            ps.executeUpdate();
            ps.close();
            
        } catch (SQLException ex) {
            System.out.println("Error GashaponChance" + ex);
            FilePrinter.printError("GashaponChance.txt", (Throwable) ex, "GashaponChance has SQL Exception");
        }
        Broadcast.broadcastGMMessage(MaplePacketCreator.serverNotice(6, "[GM 密语系统] " + chr.getName() + "  更改物品:" + MapleItemInformationProvider.getInstance().getName(itemid) + " 数量更改为" + quantity));
        FileoutputUtil.logToFile("logs/GM_LOG/GM更改转蛋物机率.txt", "\r\n" + FileoutputUtil.NowTime() + "GM: " + chr.getName() + "  更改物品:" + MapleItemInformationProvider.getInstance().getName(itemid) + " 数量更改为" + quantity);
    }

    public void AddItem(MapleCharacter chr, int itemid, int chance, boolean msg, int quantity) {
        try (Connection con = BeePool.getConnection();
             PreparedStatement ps = con.prepareStatement("INSERT INTO gashapon_items SET chance = ? , gashaponsid = ? , itemid = ? , name = ?, showmsg = ?, quantity = ?")) {
            ps.setInt(1, chance);
            ps.setInt(2, this.getId());
            ps.setInt(3, itemid);
            ps.setString(4, MapleItemInformationProvider.getInstance().getName(itemid));
            ps.setInt(5, (int) (msg ? 1 : 0));
            ps.setInt(6, quantity);
            ps.executeUpdate();
            ps.close();
            
        } catch (SQLException ex) {
            System.out.println("Error GashaponAddItem" + ex);
            FilePrinter.printError("GashaponAddItem.txt", (Throwable) ex, "GashaponAddItem has SQL Exception");
        }
        Broadcast.broadcastGMMessage(MaplePacketCreator.serverNotice(6, "[GM 密语系统] " + chr.getName() + "  新增转蛋物品:" + MapleItemInformationProvider.getInstance().getName(itemid) + " 机率设定为" + chance + " 是否上绿广:" + (msg ? "是" : "否") + " 数量设定为" + quantity));
        FileoutputUtil.logToFile("logs/GM_LOG/GM新增转蛋物机率.txt", "\r\n" + FileoutputUtil.NowTime() + "GM: " + chr.getName() + "  新增转蛋物品:" + MapleItemInformationProvider.getInstance().getName(itemid) + " 机率设定为" + chance + " 是否上绿广:" + (msg ? "是" : ("否 数量设定为" + quantity)));
    }
}
